<!-- 用户主页 -->
<template>
    <!-- emm -->
    
    <div class="box">
      <!-- 头部 -->
      <div class="top">
        <div class="top_head" :class="{ 'fixed': isHeadFixed }">
            <div class="back" @click="$router.back()">
                <svgIcon iconName="icon-fanhui1" font-size="40px" color="#fff"></svgIcon>
            </div>
            <div class="gd">
                <svgIcon icon-name="icon-gengduo" color="#fff" font-size="40px"></svgIcon>
            </div>
        </div>
        <div class="top_user">
          <div class="pic">
            <img v-if="user_in.avatar_url" :src="user_in.avatar_url" alt="用户头像">
            <img v-else :src="defaultAvatar" alt="默认头像">
          </div>
          <div class="user">
            <div class="user_name">
              {{ user_in.nickname || '未设置昵称' }}
            </div>
            <div class="user_id">
              小红书号：{{ user_in.user_id || '未设置' }}
              <svgIcon iconName="icon-erweima" color="#b3b5be" font-size="26px"></svgIcon>
            </div>
          </div>
        </div>
        <div class="top_jj">
          {{ userInfo.bio || '暂时没有简介' }}
        </div>
        <div class="top_jj_two">
          <div class="top_year" v-show="user_jj.gender !== '' && user_jj.gender !== '暂时未设置' && user_jj.gender !== '选择性别'">
          <svgIcon :iconName="user_jj.gender==='男'? 'icon-nan' : 'icon-xingbienv'" color="#b3b5be" font-size="26px"></svgIcon>
          {{ user_jj.gender }}
        </div>
        <div class="top_year">
          {{ user_jj.age }}岁
        </div>
        <div class="top_year" v-show="user_jj.area !== '' && user_jj.area !== '未设置地区' && user_jj.area !== '选择地区'">
          {{ user_jj.area}}
        </div>
        <div class="top_year" v-show="user_jj.job !== '' && user_jj.job !== '未设置职业' && user_jj.job !== '选择职业'">
          {{ user_jj.job }}
        </div>
        <div class="top_year" v-show="user_jj.school !== '' && user_jj.school !== '未设置学校' && user_jj.school !== '暂时未设置'">
          {{ user_jj.school }}
        </div>
        </div>
        <div class="top_data">
          <div class="gz">
            {{ userInfo.following_count }}
            <p>关注</p>
          </div>
          <div class="fs">
            {{ userInfo.followers_count }}
            <p>粉丝</p>
          </div>
          <div class="zan">
            0
            <p>点赞与收藏</p>
          </div>
          <div class="up_user" v-if="isFollowing" @click="handleSendMessage">
            发私信
          </div>
          <div class="sz" :class="{ 'sz_active': !isFollowing }" @click="handleFollow">
            {{ isFollowing ? '已关注' : '关注' }}
          </div>
        </div>
      </div>
      <div class="top_two" :class="{ 'fixed': isTwoFixed }">
        <div class="biji">
          笔记
        </div>
        <span class="suosuo">
          <svgIcon iconName="icon-sousuo" font-size="36px"></svgIcon>
        </span>
      </div>
      <div class="content" :class="{ 'fixed': isContFixed }">
        <div class="item" 
          v-for="note in userNotes" 
          :key="note.note_id"
          @click="handleNoteClick(note)"
        >
          <div class="item_banner">
            <img v-if="note.media_type === 'image'" :src="note.media_url" alt="">
            <VideoPoster 
              v-else-if="note.media_type === 'video'" 
              :videoSrc="note.media_url"
              width="100%"
              height="100%"
              :canvasWidth="320"
              :canvasHeight="180"
              @click="handleNoteClick(note)"
            />
          </div>
          <div v-if="note.title" class="item_title">{{ note.title }}</div>
          <div class="item_user">
            <div class="item_pic">
              <img :src="userInfo.avatar_url || defaultAvatar" alt="">
            </div>
            <div class="item_user_name">
              {{ userInfo.nickname || '未设置昵称' }}
            </div>
            <div class="item_zan">
              {{ formatTime(note.updated_at) }}
            </div>
          </div>
        </div>
      </div>
      <NavFooter />
    </div>
    
  </template>
  <script setup>
  import NavFooter from '@/components/NavFooter.vue'
  import svgIcon from '@/components/svgIcon.vue';
  import router from '@/router';
  import { ref, onMounted, onUnmounted, reactive, computed } from 'vue';
  import axios from 'axios';
  import defaultAvatar from '@/assets/czq/pic.png';
  import { useRoute } from 'vue-router';
  import { showToast, showDialog } from 'vant';
  import VideoPoster from '@/components/VideoPoster.vue';
  
  const route = useRoute();
  const userId = computed(() => route.query.userId);
  
  const isHeadFixed = ref(false);
  const isTwoFixed = ref(false);
  const isContFixed = ref(false);
  const isFollowing = ref(false);
  
  // 用户信息
  const user_in = ref({
    nickname: '',
    user_id: '',
    avatar_url: '',
  })
const userInfo = ref({
  nickname: '',
  user_id: '',
  avatar_url: '',
  bio: '',
  works_list: [],
  //关注列表
  following_list: [],
  //粉丝列表
  followers_list: [],
  //关注数
  following_count: 0,
  //粉丝数
  followers_count: 0,
});

//用户简介
const user_jj = ref({
  age: '',
  gender: '',
  area: '',
  job: '',
  school: '',
})

// 用户笔记列表
const userNotes = ref([]);

// 计算年龄的函数
const calculateAge = (birthday) => {
  if (!birthday) return '';
  const [year, month, day] = birthday.split('-').map(Number);
  const today = new Date();
  const birthDate = new Date(year, month - 1, day);
  
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age;
};

// 获取笔记媒体数据
const fetchNoteMedia = async (noteId) => {
  try {
    const response = await axios.get(`http://1.14.98.17:8765/api/notes/${noteId}/media`);
    if (response.data.success) {
      const mediaData = response.data.data[0];
      return {
        media_url: mediaData?.media_url || '',
        media_type: mediaData?.media_type || 'image' // 默认为image类型
      };
    }
    return {
      media_url: '',
      media_type: 'image'
    };
  } catch (error) {
    console.error(`获取笔记 ${noteId} 的媒体数据出错:`, error);
    return {
      media_url: '',
      media_type: 'image'
    };
  }
};

// 获取所有用户的笔记
const fetchUserNotes = async (userId) => {
  try {
    const response = await axios.get('http://1.14.98.17:8765/api/notes');
    if (response.data.success) {
      // 筛选出指定用户的笔记
      const notes = response.data.data.filter(note => note.user_id === userId);
      console.log('用户笔记数据：', notes);
      
      // 获取每个笔记的媒体数据  获取对应笔记的第一个媒体数据也就是封面 组成新的笔记数据
      const notesWithMedia = await Promise.all(
        notes.map(async (note) => {
          const mediaData = await fetchNoteMedia(note.note_id);
          return {
            ...note,
            media_url: mediaData.media_url,
            media_type: mediaData.media_type
          };
        })
      );
      
      userNotes.value = notesWithMedia;
      console.log('带媒体数据的笔记：', userNotes.value);
    } else {
      console.error('获取笔记数据失败:', response.data);
    }
  } catch (error) {
    console.error('获取笔记数据出错:', error);
  }
};

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        const userId = route.query.userId;
        if (!userId) {
            showToast('未获取到用户ID');
            return;
        }

        //获取用户基本信息
        const response = await axios.get(`http://1.14.98.17:8765/api/users/${userId}`);
        if (response.data.success === true) {
            const data = response.data.data;
            user_in.value = {
                nickname: data.nickname || '未设置昵称',
                user_id: data.user_id || '未设置小红书号',
                avatar_url: data.avatar_url || defaultAvatar,
            }
            // 获取用户详情
            const profileResponse = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}`);
            if (profileResponse.data.success === true) {
                const bio_jj = profileResponse.data.data.bio || '';
                const bioArray = bio_jj.split('。');

                // 获取关注列表
                const followingResponse = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}/following`);
                const followingCount = followingResponse.data.success ? followingResponse.data.data.following.length : 0;

                // 获取粉丝列表
                const followersResponse = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}/followers`);
                const followersCount = followersResponse.data.success ? followersResponse.data.data.followers.length : 0;

                //设置用户全部信息 
                userInfo.value = {
                    nickname: data.nickname || '未设置昵称',
                    user_id: data.user_id || '未设置小红书号',
                    avatar_url: data.avatar_url || defaultAvatar,
                    works_list: profileResponse.data.data.works_list || [],
                    following_list: profileResponse.data.data.following_list || [],
                    followers_list: profileResponse.data.data.followers_list || [],
                    following_count: followingCount,
                    followers_count: followersCount,
                    bio: bioArray[0] || '未设置简介'
                }

                user_jj.value = {
                    school: bioArray[5] || '',
                    gender: bioArray[1] || '',
                    age: calculateAge(bioArray[2]) || 20,
                    area: bioArray[3] ? bioArray[3] : '',
                    job: bioArray[4] || ''
                }
            }

            // 获取用户笔记
            fetchUserNotes(userId);
        } else {
            showToast(response.data.message || '获取用户简介信息失败');
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        showToast('获取用户信息失败');
    }
};
  
  // 添加节流函数
  const throttle = (fn, delay) => {
    let timer = null;
    return function() {
      if (timer) return;
      timer = setTimeout(() => {
        fn.apply(this, arguments);
        timer = null;
      }, delay);
    };
  };
  
  
  onMounted(() => {
    fetchUserInfo(); // 获取用户信息
    checkFollowingStatus(); // 检查关注状态
    
    const handleScroll = throttle(() => {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      
      // 头部固定
      if (scrollTop > 1) {
        isHeadFixed.value = true;
      } else {
        isHeadFixed.value = false;
      }
      
      // top_two和top_three固定
      if (scrollTop > 350) {
        isTwoFixed.value = true;
        isContFixed.value = true;
      } else {
        isTwoFixed.value = false;
        isContFixed.value = false;
      }
    }, 1);
  
    window.addEventListener('scroll', handleScroll);
    
    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll);
    });
  
  });
  
  // 添加处理surf值的函数
  const formatSurf = (surf) => {
    if (surf >= 10000) {
      return Math.floor(surf / 10000) + 'w+';
    }
    return surf;
  };
  
  // 处理笔记点击事件
  const handleNoteClick = (note) => {
    router.push({
      path: '/mecont',
      query: {
        userId: userId.value,
        noteId: note.note_id
      }
    });
  };

  // 获取当前用户的关注列表并判断是否已关注
  const checkFollowingStatus = async () => {
    try {
        const currentUserId = localStorage.getItem('user_id');
        if (!currentUserId) {
            console.error('未找到当前用户ID');
            return;
        }

        const response = await axios.get(`http://1.14.98.17:8765/api/profile/${currentUserId}/following`);
        if (response.data.success) {
            // 检查关注列表中是否包含目标用户ID
            isFollowing.value = response.data.data.following.includes(userId.value);
        }
    } catch (error) {
        console.error('获取关注列表失败:', error);
    }
  };

  // 处理关注/取消关注
  const handleFollow = async () => {
    try {
        const currentUserId = localStorage.getItem('user_id');
        if (!currentUserId) {
            showToast('请先登录');
            return;
        }

        if (isFollowing.value) {
            // 如果已关注，显示确认对话框
            showDialog({
                title: '取消关注',
                message: '确定要取消关注该用户吗？',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                className: 'custom-dialog',
                width:'500px',
                
            }).then(async () => {
                // 点击确定，发送取消关注请求
                const response = await axios.delete(`http://1.14.98.17:8765/api/profile/${currentUserId}/follow/${userId.value}`);
                if (response.data.success) {
                    isFollowing.value = false;
                    showToast('已取消关注');
                    // 更新关注数
                    userInfo.value.followers_count--;
                    
                    // 触发关注状态变化事件，通知关注页面更新数据
                    window.dispatchEvent(new CustomEvent('followStatusChanged'));
                } else {
                    showToast(response.data.message || '取消关注失败');
                }
            }).catch(() => {
                // 点击取消，不做任何操作
            });
        } else {
            // 未关注，发送关注请求
            const response = await axios.post(`http://1.14.98.17:8765/api/profile/${currentUserId}/follow/${userId.value}`);
            if (response.data.success) {
                isFollowing.value = true;
                showToast('关注成功');
                // 更新关注数
                userInfo.value.followers_count++;
                
                // 触发关注状态变化事件，通知关注页面更新数据
                window.dispatchEvent(new CustomEvent('followStatusChanged'));
            } else {
                showToast(response.data.message || '关注失败');
            }
        }
    } catch (error) {
        console.error('关注操作失败:', error);
        showToast('操作失败');
    }
  };

  // 处理发私信
  const handleSendMessage = () => {
    router.push({
      path: '/information',
      query: {
        userId: userId.value
      }
    });
  };

  // 时间计算器
const formatTime = (timeStr) => {
    if (!timeStr) return '';
    
    const now = new Date();
    const time = new Date(timeStr);
    
    // 检查时间是否有效
    if (isNaN(time.getTime())) {
        console.error('Invalid time string:', timeStr);
        return '';
    }
    
    const diff = now - time; // 时间差（毫秒）
    
    // 十分钟内
    if (diff < 10 * 60 * 1000) {
        return '刚刚';
    }
    
    // 24小时内
    if (diff < 24 * 60 * 60 * 1000) {
        const hours = Math.floor(diff / (60 * 60 * 1000));
        const minutes = Math.floor(diff / (60 * 1000));
        
        if (hours === 0) {
            return `${minutes}分钟前`;
        } else {
            return `${hours}小时前`;
        }
    }
    
    // 本年内
    if (time.getFullYear() === now.getFullYear()) {
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${month}-${day}`;
    }
    
    // 超过本年
    const year = time.getFullYear();
    const month = String(time.getMonth() + 1).padStart(2, '0');
    const day = String(time.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };


  </script>
  
  <style lang="less" scoped>
    .box {
      width: 750px;
      height: 100vh;
      background-color: #5a555c;
      position: relative;
      .top {
        width: 100%;
        // height: 700px;
        color: #fff;
        font-size: 32px;
        background: linear-gradient(to bottom, #30344d, #5a555c);
        z-index: 1000;
        .top_head {
            width: 100%;
          height: 100px;
          display: flex;
          padding: 0 35px;
          align-items: center;
          justify-content: space-between;
          transition: all 0.3s ease;
          &.fixed {
            position: fixed;
            top: 0;
            left: 0;
            z-index: 100;
            background: #30344d;
          }
        }
        .top_user {
          padding: 0 35px;
          height: 150px;
          display: flex;
          .pic {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            img {
              width: 150px;
              height: 150px;
              border-radius: 50%;
              background-size: 100% 100%;
              background-repeat: no-repeat;
            }
          }
          .user {
           margin-left: 35px;
           height: 100%;
           .user_name {
            margin-top: 30px;
            font-size: 36px;
            font-weight: 700;
           }
           .user_id {
            margin-top: 10px;
            font-size: 22px;
            color: #b3b5be;
           } 
          }
        }
        .top_jj {
          margin-left: 35px;
          margin-top: 35px;
        }
        .top_jj_two {
          display: flex;
          .top_year{
            margin-left: 35px;
            margin-top: 35px;
            padding: 8px 15px;
            font-size: 22px;
            border-radius: 20px;
            background-color: #5f677c;
            text-align: center;
          }
        }
        .top_data {
          margin-top: 10px;
          padding: 0 35px;
          height: 130px;
          display: flex;
          align-items: center;
          div {
            text-align: center;
            margin-right: 35px;
            p {
              font-size: 26px;
            }
          }
          .up_user {
            margin-left: 75px;
            width: 130px;
            height: 55px;
            line-height: 55px;
            border-radius: 30px;
            background-color: #6b666d;
            border: 1px solid #fff;
            font-size: 26px;
          }
          .sz {
            width: 100px;
            height: 55px;
            border-radius: 30px;
            background-color: #6b666d;
            border: 1px solid #fff;
            padding-top: 5px;
            margin-right: 0;
            font-size: 26px;
            line-height: 50px;
          }
          .sz_active {
            margin-left: 220px;
            color: red;
            background-color: rgb(244, 195, 195);
          }
        }
      }
      .top_two {
        width: 100%;
        border-radius: 20px 20px 0 0;
        background-color: #fff;
        height: 80px;
        padding: 0 35px;
        display: flex;
        align-items: center;
        font-size: 32px;
        &.fixed {
          position: fixed;
          top: 100px;
          left: 0;
          width: 100%;
          z-index: 101;
          background: #fff;
          border-radius:0;
        }
        div {
          width: 80px;
          height: 50px;
          border-bottom: 5px solid red;
          text-align: center;
          color: #87888e;
          margin-right: 60px;
        }
        span {
          display: block;
          margin-left: 260px;
        }
        .two_active {
          color: #000;
        }
      }
      .content {
        width: 750px;
        column-count: 2; /* 设置列数 */
        column-gap: 10px; /* 列间距 */
        background-color: #fafafa;
        min-height: 1500px;
        padding: 0 10px;
        padding-bottom: 100px;
        &.fixed {
          margin-top: 80px;
          width: 100%;
          z-index: 999;
        }
        .item {
          width: 360px;
          margin-bottom: 20px; /* 上下间距 */
          break-inside: avoid; /* 防止item被分割到不同列 */
          background-color: #fff;
          display: flex;
          flex-direction: column;
          height: fit-content;
          border-radius: 8px;
          overflow: hidden;
  
          .item_banner {
            position: relative;
            width: 100%;
            img {
              width: 100%;
              height: auto; /* 让图片高度自适应 */
              object-fit: cover; /* 保持图片比例 */
            }
            video {
              width: 100%;
              height: auto; /* 让图片高度自适应 */
              object-fit: cover; /* 保持图片比例 */
            }
            span {
              display: block;
              position: absolute;
              left: 15px;
              bottom: 15px;
              padding: 0 10px;
              height: 40px;
              border-radius: 20px;
              background-color: rgba(0, 0, 0, .4);
              text-align: center;
              line-height: 40px;
              font-size: 22px;
              color: #fff;
            }
          }
          .item_title {
            width: 100%;
            height: 60px;
            line-height: 60px;
            color: #000;
            font-size: 28px;
            padding-left: 20px;
            overflow: hidden;
          }
          .item_user {
            display: flex;
            width: 100%;
            height: 60px;
            line-height: 60px;
            color: #87888e;
            padding-left: 20px;
            .item_pic {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              img {
                border-radius: 50%;
                width: 100%;
                height: 100%;
                margin-bottom: 5px;
              }
            }
            .item_user_name {
              width: 200px;
              margin-left: 20px;
              font-size: 22px;
            }
            .item_zan {
              margin-left: 20px;
              width: 80px;
              font-size: 26px;
              color: #87888e;
            }
          }
        }
      }
    }
</style>